//
//  HMOAuthViewController.swift
//  Weibo-swift
//
//  Created by GD on 16/9/20.
//  Copyright © 2016年 geduo. All rights reserved.
//   https://api.weibo.com/oauth2/authorize?client_id=2461615762&redirect_uri=http://www.baidu.com

//  https://www.baidu.com/?code=62e9025549ecaeff28a1a48273a9abad 

import UIKit
import SVProgressHUD

let WeiboAppKey : String = "2461615762"
let WeoboAppSecret : String = "c02318ad41df10197e807191a51015c4"
let WeiboRedirect_Uri = "http://www.baidu.com"
//会调页   http://www.baidu.com

class HMOAuthViewController: UIViewController {
    
    private lazy var webView : UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        requestLogin()
        webView.delegate = self
        
        setupNavUI()
        
    }

    private func requestLogin(){
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    }
    
    private func setupNavUI(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
//    //获取Token
//    func requestAccessToken(code:String) {
//        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            if error != nil{
//                print("网络有问题:\(error)")
//            }
//            
//            // 转模型print(response)
//            guard let dict = response as? [String: Any] else {
//                print("字典有问题")
//                return
//            }
//            
//            let userAccount = HMUserAccount(dict: dict)
//            //获取用户信息
//            print(userAccount.access_token)
//            
//            self.requestUserInfo(userAccount: userAccount)
//        }
//    }
//    
//    func requestUserInfo(userAccount:HMUserAccount) -> Void {
//        HMNetworkTools.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid, callBack: { (response, error) in
//            if error != nil{
//                print("网络有问题:\(error)")
//            }
//            
//            // 转模型print(response)
//            guard let dict = response as? [String: Any] else {
//                print("字典有问题")
//                return
//            }
//            
//            let name = dict["name"]
//            let profile_image_url = dict["profile_image_url"]
//            
//            userAccount.name = name as? String
//            userAccount.profile_image_url = profile_image_url as! String?
//            
//            print(userAccount.name)
//            
//            userAccount.saveUserAccount()
//        })
//    }
    
    //  MARK: -- 点击事件处理
    @objc private func cancelAction() {
        
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFillAction() {
        
        print("自动填充")
        
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15300230977';document.getElementById('passwd').value = '2012213576bss'")
        
    }
}

// MARK : -- UIWebViewDelegate
extension HMOAuthViewController : UIWebViewDelegate{
    
    //  开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        SVProgressHUD.dismiss()
        //可选类型,url可能含有中文
        guard let url = request.url else {
            print("url 为nil")
            return false
        }
        
       // print(url.absoluteString)
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {//该url不是我们关心的
            return true  //
        }
        //取地址栏中的参数
        if let query = url.query , query.hasPrefix("code="){
            
            let code = query.substring(from: "code=".endIndex)
//            print(code)
//            requestAccessToken(code: code)
            HMUserAccountViewModel.sharedUserAccountViewModel.requestAccessToken(code: code,callBack: {
                (isSucess) in
                
                if (isSucess){
                    print("登录成功");//发通知
                    //要等到dismiss 完成以后,才可以发送通知
                    self.dismiss(animated: false, completion: { 
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                    })
                }
            })
        }else{//取消授权
            dismiss(animated: true, completion: nil)
        }
        
        
        return false
    }
}
